import React, { useState, useRef } from 'react'
import { bannerAdd } from './../../api/banner'
import { useHistory } from 'react-router-dom'
function BannerAdd() {
  const history = useHistory()

  const [ alt, setAlt ] = useState('')
  const [ link, setLink ] = useState('')
  const [ img, setImg ] = useState('')

  const fileRef = useRef()

  const getImg = () => {
    // 预览图片
    const file = fileRef.current.files[0]
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = function () {
      setImg(this.result)
    }
  }
  return (
    <div>
      <input type="text" onChange = { (event) => {
        setAlt(event.target.value)
      } } placeholder="alt"/> <br />
      <input type="text" onChange = { (event) => {
        setLink(event.target.value)
      } } placeholder="link"/> <br />
      <input type="file"  onChange = { getImg } ref = { fileRef }/> <br />
      <img src={ img } alt={ alt }/>
      <button onClick = { () => {
        // console.log({
        //   alt,
        //   link,
        //   img
        // })
        const data = { alt, link, img }
        bannerAdd(data).then(() => {
          history.push('/banner/list')
        })
      }}>提交</button>
    </div>
  )
}

export default BannerAdd
